package com.terminal;

import java.util.Map;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.Paint.FontMetrics;
import android.util.AttributeSet;
import android.view.SurfaceView;

public class TerminalView extends SurfaceView {
	CharPanel cp = null;
	int fontWidth = 1;
	int fontHeight = 1;
	int offsetX = 0;
	int offsetY = 0;
	public int fontSize = 12;
	int fontAsc = 0;
	public TerminalSocket ts = null;

	public TerminalView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
	}

	public TerminalView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
	}

	public TerminalView(Context context, AttributeSet attrs,int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh)
	{
		super.onSizeChanged(w, h, oldw, oldh);
		Paint paint = new Paint();
		paint.setTypeface(Typeface.MONOSPACE);
		paint.setTextSize(fontSize);
		paint.setAntiAlias(true);
		fontWidth = (int)paint.measureText("W");
		fontHeight = (int)paint.getFontSpacing();
		FontMetrics fm = paint.getFontMetrics();
		fontAsc = (int)fm.ascent;
		
		
		cp = new CharPanel((int)(w / fontWidth), (int)(h / fontHeight));
		offsetX = (w - fontWidth * cp.iSizeX) / 2;
		offsetY = (h - fontHeight * cp.iSizeY) / 2;
		ts.X = (byte)(w / fontWidth);
		ts.Y = (byte)(h / fontHeight);	
		ts.SocketStart();
	}
	
	@Override
	public void draw(Canvas canvas)
	{
		Paint paint = new Paint();
		paint.setTypeface(Typeface.MONOSPACE);
		paint.setAntiAlias(true);
		paint.setTextSize(fontSize);
		
		if(cp == null) return;
		canvas.drawColor(Color.BLACK);
		for(int j = 0; j < cp.iSizeY; j++)
		{
			if(cp.isDirty && cp.isDirtyLine[j])
			{
				for(int i = 0; i < cp.iSizeX; i++)
				{
					canvas.save();
					canvas.clipRect(i * fontWidth + offsetX, j * fontHeight + offsetY, (i + 1) *fontWidth + offsetX, (j + 1) * fontHeight + offsetY);
					canvas.drawColor(cp.Matrix[i][j].clrBg);
					canvas.restore();			
					paint.setColor(cp.Matrix[i][j].clrFg);
					canvas.drawText("" + cp.Matrix[i][j].chr , i*fontWidth + offsetX, j * fontHeight - fontAsc + offsetY, paint);
				}
			}
		}
		
	}
	

}
